/**
 * 音频文件加载器
 * 用于加载预生成的WAV音效文件
 */

// 音效文件路径映射
const SOUND_FILES = {
  startup: 'resources/audio/startup.wav',
  success: 'resources/audio/success.wav',
  error: 'resources/audio/error.wav',
  notification: 'resources/audio/notification.wav'
} as const;

type SoundType = keyof typeof SOUND_FILES;

// 音频缓存
const audioCache = new Map<SoundType, AudioBuffer>();

/**
 * 加载音频文件
 */
export async function loadAudioFile(soundType: SoundType): Promise<AudioBuffer> {
  // 检查缓存
  if (audioCache.has(soundType)) {
    return audioCache.get(soundType)!;
  }

  try {
    const audioContext = new (window.AudioContext || (window as any).webkitAudioContext)();
    const filePath = SOUND_FILES[soundType];

    // 在Electron环境中，我们需要使用file://协议
    const response = await fetch(`file://${process.cwd()}/${filePath}`);
    const arrayBuffer = await response.arrayBuffer();
    const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);

    // 缓存音频
    audioCache.set(soundType, audioBuffer);

    return audioBuffer;
  } catch (error) {
    console.error(`加载音效文件失败 (${soundType}):`, error);
    throw error;
  }
}

/**
 * 播放音频缓冲区
 */
export async function playAudioBuffer(audioBuffer: AudioBuffer, volume: number = 0.5): Promise<void> {
  return new Promise((resolve, reject) => {
    try {
      const audioContext = new (window.AudioContext || (window as any).webkitAudioContext)();

      // 创建音源
      const source = audioContext.createBufferSource();
      source.buffer = audioBuffer;

      // 创建音量控制
      const gainNode = audioContext.createGain();
      gainNode.gain.value = volume;

      // 连接音频节点
      source.connect(gainNode);
      gainNode.connect(audioContext.destination);

      // 播放完成时resolve
      source.onended = () => {
        resolve();
      };

      // 开始播放
      source.start(0);

      // 设置超时防止长时间等待
      setTimeout(() => {
        resolve();
      }, 5000);
    } catch (error) {
      reject(error);
    }
  });
}

/**
 * 播放指定类型的音效
 */
export async function playSound(soundType: SoundType, volume: number = 0.5): Promise<void> {
  try {
    const audioBuffer = await loadAudioFile(soundType);
    await playAudioBuffer(audioBuffer, volume);
  } catch (error) {
    console.warn(`播放音效失败 (${soundType}):`, error);
  }
}

/**
 * 预加载所有音效文件
 */
export async function preloadAllSounds(): Promise<void> {
  const soundTypes: SoundType[] = ['startup', 'success', 'error', 'notification'];

  try {
    await Promise.all(
      soundTypes.map(async (soundType) => {
        try {
          await loadAudioFile(soundType);
          console.log(`音效文件已预加载: ${soundType}`);
        } catch (error) {
          console.warn(`预加载音效文件失败: ${soundType}`, error);
        }
      })
    );
    console.log('所有音效文件预加载完成');
  } catch (error) {
    console.error('预加载音效文件时出错:', error);
  }
}

export type { SoundType };
